<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('修改文章')"/>
    <th:block th:include="include :: summernote-css"/>
    <th:block th:include="include :: select2-css"/>
    <script th:inline="javascript">
        var ctx = [[${#request.getContextPath()}]];
        var serverUrl = [[${
            #httpServletRequest
            .scheme + "://" + #httpServletRequest.serverName + ":" + #httpServletRequest.serverPort
        }]];
    </script>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-knowledgepool-edit" th:object="${knowledgepool}">
        <input name="id" th:field="*{id}" type="hidden">
        <div class="form-group">
            <label class="col-sm-3 control-label">标题：</label>
            <div class="col-sm-8">
                <input name="title" th:field="*{title}" class="form-control" type="text">
            </div>
            <div></div>
            <label class="col-sm-3 control-label">关键词：</label>
            <div class="col-sm-8">
                <input name="keyword" th:field="*{keyword}" class="form-control" type="text">
            </div>
            <div></div>
            <label class="col-sm-3 control-label">文章权限标识：</label>
            <div class="col-sm-8">
                <select class="form-control" id="permissionType" name="permissionType"
                        onchange="toggleCustomerSelect()">
                    <!-- 选项将通过 JavaScript 动态加载 -->
                </select>
            </div>
        </div>
        <div class="form-group" id="customerSelectDiv" style="display:none;">
            <label class="col-sm-3 control-label">选择可见部门：</label>
            <div class="col-sm-8">
                <select class="form-control select2" id="deptSelect" multiple>
                </select>
                <input id="deptList" name="deptList" th:field="*{deptList}" type="hidden">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">内容：</label>
            <div class="col-sm-8">
                <input type="hidden" class="form-control" th:field="*{content}">
                <div class="summernote" id="content"></div>
            </div>
        </div>

    </form>
</div>
<th:block th:include="include :: footer"/>
<th:block th:include="include :: summernote-js"/>
<th:block th:include="include :: select2-js"/>
<script th:inline="javascript">
    var prefix = ctx + "system/knowledgepool";
    $("#form-knowledgepool-edit").validate({
        focusCleanup: true
    });

    function loadPermissionTypes() {
        var baseUrl = window.location.protocol + "//" + window.location.host;
        var url = baseUrl + "/system/dict/data/list";

        $.ajax({
            url: url,
            type: "POST",
            dataType: "json",
            contentType: "application/x-www-form-urlencoded",
            data: {
                pageSize: 10,
                pageNum: 1,
                orderByColumn: "dictSort",
                isAsc: "asc",
                dictType: "sys_knowledge_permission"
            },
            success: function (result) {
                var permissionSelect = $("#permissionType");
                permissionSelect.empty();

                if (result.rows && result.rows.length > 0) {
                    $.each(result.rows, function (index, dict) {
                        var isSelected = dict.dictValue === [[${knowledgepool.permissionType}]];
                        permissionSelect.append(new Option(dict.dictLabel, dict.dictValue, isSelected, isSelected));
                    });
                } else {
                    permissionSelect.append(new Option("暂无可选权限类型", "", false, false));
                }

                permissionSelect.trigger('change');
            },
            error: function (xhr, status, error) {
                console.error("请求失败:", {
                    url: url,
                    status: status,
                    error: error,
                    response: xhr.responseText
                });
                $.modal.alertError("加载权限类型失败");
            }
        });
    }

    function toggleCustomerSelect() {
        var permissionType = $("#permissionType").val();
        var customerSelectDiv = $("#customerSelectDiv");

        if (permissionType === "客户类") {
            customerSelectDiv.show();
            $("#deptSelect").attr("required", "required");
            loadDeptOptions();
        } else {
            customerSelectDiv.hide();
            $("#deptSelect").removeAttr("required");
            $("#deptSelect").empty().trigger('change');
        }
    }

    function loadDeptOptions() {
        $.ajax({
            url: ctx + "system/dept/list",
            type: "POST",
            dataType: "json",
            success: function (result) {
                var deptSelect = $("#deptSelect");
                deptSelect.empty();

                if (result && result.length > 0) {
                    // 按照parentId组织部门树结构
                    var deptMap = {};
                    var topDepts = [];

                    // 首先建立映射关系
                    $.each(result, function (index, dept) {
                        dept.children = [];
                        deptMap[dept.deptId] = dept;
                    });

                    // 构建树形结构
                    $.each(result, function (index, dept) {
                        if (dept.parentId === "0") {
                            topDepts.push(dept);
                        } else {
                            var parent = deptMap[dept.parentId];
                            if (parent) {
                                parent.children.push(dept);
                            }
                        }
                    });

                    // 递归添加选项
                    function addOptions(depts, level) {
                        $.each(depts, function (index, dept) {
                            var indent = "";
                            for (var i = 0; i < level; i++) {
                                indent += "　";
                            }
                            if (level > 0) {
                                indent += "├─ ";
                            }

                            deptSelect.append(new Option(indent + dept.deptName, dept.deptId, false, false));

                            if (dept.children && dept.children.length > 0) {
                                addOptions(dept.children, level + 1);
                            }
                        });
                    }

                    addOptions(topDepts, 0);
                } else {
                    deptSelect.append(new Option("暂无可选部门", "", false, false));
                }

                // 如果有预设的部门列表，则设置选中
                var deptList = [[${knowledgepool.deptList}]];
                if (deptList) {
                    $("#deptSelect").val(deptList.split(',')).trigger('change');
                }
            },
            error: function (xhr, status, error) {
                $.modal.alertError("加载部门列表失败");
            }
        });
    }

    $(document).ready(function () {
        // 加载权限类型
        loadPermissionTypes();

        // 初始化select2
        $("#deptSelect").select2({
            placeholder: "请选择可见部门",
            allowClear: true,
            width: '100%',
            language: "zh-CN",
            multiple: true,
            minimumResultsForSearch: 0,
            templateResult: function (data) {
                return data.text;
            }
        });

        // 初始化显示状态
        toggleCustomerSelect();
    });

    function submitHandler() {
        if ($.validate.form()) {
            var permissionType = $("#permissionType").val();
            if (permissionType === "客户类") {
                var selectedDepts = $("#deptSelect").val();
                if (!selectedDepts || selectedDepts.length === 0) {
                    $.modal.alertWarning("请选择可见部门");
                    return;
                }
                $("#deptList").val(selectedDepts.join(','));
            }
            $.operate.save(prefix + "/edit", $('#form-knowledgepool-edit').serialize());
        }
    }

    $(function () {
        $('.summernote').each(function (i) {
            $('#' + this.id).summernote({
                lang: 'zh-CN',
                minHeight: 600,
                widths: 500,
                dialogsInBody: true,
                callbacks: {
                    onChange: function (contents, $edittable) {
                        $("input[name='" + this.id + "']").val(contents);
                    },
                    onImageUpload: function (files) {
                        var obj = this;
                        var data = new FormData();
                        data.append("file", files[0]);
                        $.ajax({
                            type: "post",
                            url: ctx + "common/upload",
                            data: data,
                            cache: false,
                            contentType: false,
                            processData: false,
                            dataType: 'json',
                            success: function (result) {
                                if (result.code == web_status.SUCCESS) {
                                    $('#' + obj.id).summernote('insertImage', result.url);
                                } else {
                                    $.modal.alertError(result.msg);
                                }
                            },
                            error: function (error) {
                                $.modal.alertWarning("图片上传失败。");
                            }
                        });
                    }
                }
            });
            var content = $("input[name='" + this.id + "']").val();
            $('#' + this.id).summernote('code', content);
        })
    });
</script>
</body>
</html>